/**
 * 邮件发送模板-操作详情页
 */
import React, { memo } from 'react';
import { Form, Card, Popover } from 'antd';
import { get as getPath } from 'object-path';
import FileUpload from '@/components/Custom/FileUpload';
import { useRequest, defaultFormatResult } from '@/hooks';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BraftEditor from 'braft-editor';
import { transformFileList } from '../utils';
import { PreviewModal } from './containers';
import { getEmailTemplateOperateDetail } from './service';
import styles from './index.less';

const templateTypeList = [
    { label: '发布/上线模板', value: 1 },
    { label: '更新模板', value: 2 },
    { label: '下线模板', value: 3 }
];
const OriginContent = memo(({ info, keyName, changeKeyName, originText, currentText, changeColor = true }) => {
    const changeState = info?.changeMark[changeKeyName];
    return changeState ? <Popover overlayClassName={changeColor ? '' : styles.originContentPopover} content={originText || info?.changeMarkContent[changeKeyName]} title="原始内容">
        <span style={{ color: changeColor ? 'red' : '' }}>{currentText || getPath(info, keyName, '')}</span>
    </Popover> : currentText || getPath(info, keyName, '')
});


const EmailTemplateOperateDetail = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const modalRef = React.useRef(null);

    const { data: info, loading, run: fetchDetail } = useRequest(getEmailTemplateOperateDetail, {
        manual: true,
        ...defaultFormatResult
    });

    React.useEffect(() => {
        if (query?.id) {
            fetchDetail(query?.id);
        }
    }, []);

    const recruitColumns = React.useMemo(() => {
        if (info?.recruitColumn) {
            try {
                const columns = [];
                const recruitColumn = JSON.parse(info.recruitColumn);
                Object.keys(recruitColumn).forEach(key => {
                    columns.push(recruitColumn[key]);
                });
                return columns
            } catch (e) {
                return []
            }
        }
        return [];
    }, [info]);
    const changeRecruitColumns = React.useMemo(() => {
        if (info?.changeMarkContent?.changeRecruitColumn) {
            try {
                const columns = [];
                const recruitColumn = JSON.parse(info?.changeMarkContent?.changeRecruitColumn);
                Object.keys(recruitColumn).forEach(key => {
                    columns.push(recruitColumn[key]);
                });
                return columns
            } catch (e) {
                return []
            }
        }
        return [];
    }, [info]);
    React.useEffect(() => {
        if (getPath(info, 'recruitChannelTemplateRecordFile')) {
            form.setFieldsValue({
                attachmentList: transformFileList(getPath(info, 'recruitChannelTemplateRecordFile', []))
            });
        }
        if (getPath(info, ['changeMarkContent', 'changeAttachment'])) {
            form.setFieldsValue({
                changeAttachmentList: transformFileList(getPath(info, ['changeMarkContent', 'changeAttachment']), [])
            });
        }
    }, [info]);

    const handlePreview = e => {
        e.preventDefault();
        const { subject, openingRemarks } = info;
        let str = openingRemarks || '';
        str += '<br/>';
        recruitColumns.forEach(item => {
            str += `<p style="text-indent:${6 - item?.length}em;">${item}：</p>`;
        });
        modalRef.current.show({
            subject: subject || '',
            openingRemarks: str,
            resourceRelation: form.getFieldValue('attachmentList') || null
        });
    };

    return (
        <PageHeaderWrapper>
            <Card title="模板详情" bordered={false} loading={loading}>
                <Form className={styles.formWrap} style={{ marginTop: 24 }}>
                    <Form.Item label="名称" className={styles.detailItem} required>
                        <OriginContent info={info} keyName="templateName" changeKeyName="changeTemplateName"/>
                    </Form.Item>
                    <Form.Item label="邮件主题" className={styles.detailItem} required>
                        <OriginContent info={info} keyName="subject" changeKeyName="changeSubject"/>
                    </Form.Item>
                    <Form.Item label="模板类型" className={styles.detailItem} required>
                        <OriginContent
                            info={info}
                            keyName="templateType"
                            changeKeyName="changeTemplateType"
                            originText={templateTypeList.find(item => item.value === getPath(info, ['changeMarkContent', 'changeTemplateType']))?.label || ''}
                            currentText={templateTypeList.find(item => item.value === getPath(info, 'templateType'))?.label || ''}
                        />
                    </Form.Item>
                    <Form.Item label="是否通用" className={styles.detailItem}>
                        <OriginContent
                            info={info}
                            keyName="generalType"
                            changeKeyName="changeGeneralType"
                            originText={getPath(info, ['changeMarkContent', 'changeGeneralType'], false) ? '是' : '否'}
                            currentText={getPath(info, 'generalType', false) ? '是' : '否'}
                        />
                    </Form.Item>
                    <Form.Item label="模板附件" className={styles.detailItem}>
                        <OriginContent
                            info={info}
                            changeColor={false}
                            changeKeyName="changeAttachment"
                            originText={
                                getFieldDecorator('changeAttachmentList')(<FileUpload disabled> </FileUpload>)
                            }
                            currentText={
                                <div
                                    style={{ borderRadius: '4px', border: getPath(info, ['changeMark', 'changeAttachment'], null) ? '1px solid red' : '' }}
                                >
                                    { getFieldDecorator('attachmentList')(<FileUpload disabled> </FileUpload>) }
                                </div>
                            }
                        />
                    </Form.Item>
                    <Form.Item label="邮件内容" className={styles.detailItem} required>
                        招聘需求字段+其他内容&nbsp;&nbsp;<a onClick={handlePreview}>效果预览</a>
                    </Form.Item>
                    <Form.Item label="招聘需求字段" className={styles.detailItem} required>
                        <OriginContent
                            info={info}
                            changeKeyName="changeRecruitColumn"
                            originText={changeRecruitColumns.join('；')}
                            currentText={recruitColumns?.join('；')}
                        />
                    </Form.Item>
                    <Form.Item label="其他内容" required>
                        <OriginContent
                            info={info}
                            changeColor={false}
                            changeKeyName="changeOpeningRemarks"
                            originText={
                                <BraftEditor
                                    controls={[]}
                                    readOnly
                                    contentStyle={{ minWidth: 400, height: 200 }}
                                    value={BraftEditor.createEditorState(getPath(info, ['changeMarkContent', 'changeOpeningRemarks'], null))}
                                />
                            }
                            currentText={
                                <BraftEditor
                                    style={{ borderColor: getPath(info, ['changeMark', 'changeOpeningRemarks'], null) ? 'red' : '' }}
                                    controls={[]}
                                    readOnly
                                    contentStyle={{ height: 600 }}
                                    value={BraftEditor.createEditorState(getPath(info, 'openingRemarks', null))}
                                />
                            }
                        />
                    </Form.Item>
                </Form>
                <PreviewModal ref={modalRef} />
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(EmailTemplateOperateDetail);
